// 游戏常量
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const DIRECTIONS = {
    UP: { x: 0, y: -1 },
    DOWN: { x: 0, y: 1 },
    LEFT: { x: -1, y: 0 },
    RIGHT: { x: 1, y: 0 }
};

// 游戏状态
let snake = [];
let food = {};
let direction = DIRECTIONS.RIGHT;
let nextDirection = DIRECTIONS.RIGHT;
let score = 0;
let gameSpeed = 5;
let gameInterval;
let isPaused = false;
let isGameOver = false;

// DOM元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const speedSlider = document.getElementById('speedSlider');
const speedValue = document.getElementById('speedValue');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const restartBtn = document.getElementById('restartBtn');



// 键盘控制
document.addEventListener('keydown', (e) => {
    switch (e.key) {
        case 'ArrowUp':
            if (direction !== DIRECTIONS.DOWN) nextDirection = DIRECTIONS.UP;
            break;
        case 'ArrowDown':
            if (direction !== DIRECTIONS.UP) nextDirection = DIRECTIONS.DOWN;
            break;
        case 'ArrowLeft':
            if (direction !== DIRECTIONS.RIGHT) nextDirection = DIRECTIONS.LEFT;
            break;
        case 'ArrowRight':
            if (direction !== DIRECTIONS.LEFT) nextDirection = DIRECTIONS.RIGHT;
            break;
        case ' ':
            if (!isGameOver) {
                isPaused = !isPaused;
                pauseBtn.textContent = isPaused ? '继续' : '暂停';
            }
            break;
    }
});

// 初始化游戏
function initGame() {
    // 初始化蛇
    snake = [
        { x: 10, y: 10 },
        { x: 9, y: 10 },
        { x: 8, y: 10 }
    ];
    
    // 初始化食物
    generateFood();
    
    // 重置游戏状态
    direction = DIRECTIONS.RIGHT;
    nextDirection = DIRECTIONS.RIGHT;
    score = 0;
    scoreElement.textContent = score;
    isGameOver = false;
    isPaused = false;
    foodEaten = false;
    
    // 绘制初始状态
    draw();
    
    // 启动游戏循环
    if (gameInterval) {
        clearInterval(gameInterval);
    }
    gameInterval = setInterval(gameLoop, 1000 / gameSpeed);
}

// 生成食物
function generateFood() {
    food = {
        x: Math.floor(Math.random() * GRID_SIZE),
        y: Math.floor(Math.random() * GRID_SIZE)
    };
    
    // 确保食物不会生成在蛇身上
    for (let segment of snake) {
        if (segment.x === food.x && segment.y === food.y) {
            return generateFood();
        }
    }
}

// 游戏主循环
function gameLoop() {
    if (isPaused || isGameOver) return;
    
    // 更新蛇的位置
    moveSnake();
    
    // 检查碰撞
    checkCollisions();
    
    // 检查是否吃到食物
    checkFood();
    
    // 绘制游戏
    draw();
}

// 移动蛇
function moveSnake() {
    direction = nextDirection;
    
    // 创建新的蛇头
    const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    
    // 添加新的蛇头
    snake.unshift(head);
    
    // 移除蛇尾（除非吃到食物）
    if (!foodEaten) {
        snake.pop();
    }
}

// 检查碰撞
function checkCollisions() {
    const head = snake[0];
    
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
        gameOver();
        return;
    }
    
    // 检查自身碰撞
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver();
            return;
        }
    }
}

// 检查食物
function checkFood() {
    const head = snake[0];
    
    if (head.x === food.x && head.y === food.y) {
        // 增加分数
        score += 10;
        scoreElement.textContent = score;
        
        // 生成新食物
        generateFood();
        
        // 标记食物已被吃掉
        foodEaten = true;
    } else {
        foodEaten = false;
    }
}

// 游戏结束
function gameOver() {
    isGameOver = true;
    clearInterval(gameInterval);
    alert(`游戏结束！你的分数是: ${score}`);
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格背景
    drawGrid();
    
    // 绘制食物
    drawFood();
    
    // 绘制蛇
    drawSnake();
}

// 绘制网格
function drawGrid() {
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 0.5;
    
    for (let i = 0; i < GRID_SIZE; i++) {
        // 水平线
        ctx.beginPath();
        ctx.moveTo(0, i * CELL_SIZE);
        ctx.lineTo(canvas.width, i * CELL_SIZE);
        ctx.stroke();
        
        // 垂直线
        ctx.beginPath();
        ctx.moveTo(i * CELL_SIZE, 0);
        ctx.lineTo(i * CELL_SIZE, canvas.height);
        ctx.stroke();
    }
}

// 绘制食物
function drawFood() {
    ctx.fillStyle = '#FF5252';
    ctx.beginPath();
    ctx.arc(
        food.x * CELL_SIZE + CELL_SIZE / 2,
        food.y * CELL_SIZE + CELL_SIZE / 2,
        CELL_SIZE / 2 - 2,
        0,
        Math.PI * 2
    );
    ctx.fill();
    
    // 食物高光效果
    ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.beginPath();
    ctx.arc(
        food.x * CELL_SIZE + CELL_SIZE / 3,
        food.y * CELL_SIZE + CELL_SIZE / 3,
        CELL_SIZE / 6,
        0,
        Math.PI * 2
    );
    ctx.fill();
}

// 绘制蛇
function drawSnake() {
    // 绘制蛇身
    for (let i = 0; i < snake.length; i++) {
        const segment = snake[i];
        
        // 蛇头
        if (i === 0) {
            ctx.fillStyle = '#4CAF50';
            ctx.fillRect(
                segment.x * CELL_SIZE,
                segment.y * CELL_SIZE,
                CELL_SIZE,
                CELL_SIZE
            );
            
            // 绘制蛇头眼睛
            drawEyes(segment);
        } 
        // 蛇身
        else {
            ctx.fillStyle = '#8BC34A';
            ctx.fillRect(
                segment.x * CELL_SIZE,
                segment.y * CELL_SIZE,
                CELL_SIZE,
                CELL_SIZE
            );
        }
    }
}

// 绘制蛇头眼睛
function drawEyes(head) {
    ctx.fillStyle = 'white';
    
    // 根据方向绘制眼睛位置
    if (direction === DIRECTIONS.RIGHT) {
        // 右眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.7,
            head.y * CELL_SIZE + CELL_SIZE * 0.3,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
        
        // 左眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.7,
            head.y * CELL_SIZE + CELL_SIZE * 0.7,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
    } else if (direction === DIRECTIONS.LEFT) {
        // 右眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.3,
            head.y * CELL_SIZE + CELL_SIZE * 0.3,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
        
        // 左眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.3,
            head.y * CELL_SIZE + CELL_SIZE * 0.7,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
    } else if (direction === DIRECTIONS.UP) {
        // 右眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.3,
            head.y * CELL_SIZE + CELL_SIZE * 0.3,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
        
        // 左眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.7,
            head.y * CELL_SIZE + CELL_SIZE * 0.3,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
    } else if (direction === DIRECTIONS.DOWN) {
        // 右眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.3,
            head.y * CELL_SIZE + CELL_SIZE * 0.7,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
        
        // 左眼
        ctx.beginPath();
        ctx.arc(
            head.x * CELL_SIZE + CELL_SIZE * 0.7,
            head.y * CELL_SIZE + CELL_SIZE * 0.7,
            CELL_SIZE * 0.1,
            0,
            Math.PI * 2
        );
        ctx.fill();
    }
}

// 事件监听
function setupEventListeners() {
    // 键盘控制
    document.addEventListener('keydown', (e) => {
        switch (e.key) {
            case 'ArrowUp':
                if (direction !== DIRECTIONS.DOWN) {
                    nextDirection = DIRECTIONS.UP;
                }
                break;
            case 'ArrowDown':
                if (direction !== DIRECTIONS.UP) {
                    nextDirection = DIRECTIONS.DOWN;
                }
                break;
            case 'ArrowLeft':
                if (direction !== DIRECTIONS.RIGHT) {
                    nextDirection = DIRECTIONS.LEFT;
                }
                break;
            case 'ArrowRight':
                if (direction !== DIRECTIONS.LEFT) {
                    nextDirection = DIRECTIONS.RIGHT;
                }
                break;
        }
    });
    
    // 速度滑块
    speedSlider.addEventListener('input', () => {
        gameSpeed = speedSlider.value;
        speedValue.textContent = gameSpeed;
        
        if (gameInterval) {
            clearInterval(gameInterval);
            gameInterval = setInterval(gameLoop, 1000 / gameSpeed);
        }
    });
    
    // 开始按钮
    startBtn.addEventListener('click', () => {
        initGame();
    });
    
    // 暂停按钮
    pauseBtn.addEventListener('click', () => {
        if (!isGameOver) {
            if (!isPaused) {
                isPaused = true;
                pauseBtn.textContent = '继续';
            } else {
                isPaused = false;
                pauseBtn.textContent = '暂停';
            }
        }
    });
    
    // 重新开始按钮
    restartBtn.addEventListener('click', () => {
        clearInterval(gameInterval);
        isPaused = false;
        pauseBtn.textContent = '暂停';
        initGame();
    });
}

// 页面加载完成后初始化事件监听
window.addEventListener('DOMContentLoaded', setupEventListeners);